using System;
using System.Collections.Generic;
using System.Linq;
using BepInEx;
using HarmonyLib;
using Hearthstone;
using Hearthstone.Progression;
using PegasusLettuce;
using PegasusShared;
using PegasusUtil;
using UnityEngine;

namespace Mercenary
{
    public static class UtilsMap
    {
        public static bool m_bNeedComplete=true;
        public static Map m_currMap=MapConst.H1_1;

        public static void SelectMap()
        {
            //更新
            if (UtilsGui.modeConf.m_id == UiItemConst.模式_刷全图.m_id ||
                UtilsGui.modeConf.m_id == UiItemConst.模式_挂机收菜.m_id)
            {
                m_bNeedComplete=true;
            }
            else if (UtilsGui.modeConf.m_id == UiItemConst.模式_刷碎片.m_id)
            {
                m_bNeedComplete=false;
                m_currMap = MapConst.N2_5;
            }
            else if (UtilsGui.modeConf.m_id == UiItemConst.模式_自动解锁地图.m_id)
            {
                m_bNeedComplete=true;
                m_currMap = GetUnCompleteMap();
            }
            else if (UtilsGui.modeConf.m_id == UiItemConst.模式_自动佣兵任务.m_id ||
                     UtilsGui.modeConf.m_id == UiItemConst.模式_自动主线任务.m_id)
            {
                bool bFind=false;
                if(UtilsGui.modeConf.m_id == UiItemConst.模式_自动佣兵任务.m_id)
                {
                    TaskUtils.UpdateMercTask();
                }
                else TaskUtils.UpdateMainLineTask();
                foreach (Task task in TaskUtils.GetTaskList())
                {
                    UtilsLog.Log("[地图信息识别] 尝试任务地图: " + task.Map);
                    m_currMap = GetMapFromName(task.Map);
                    if (m_currMap != null && MapCompleted(m_currMap))
                    {
                        UtilsLog.Log("[地图信息识别] 成功找到任务地图: " + task.Map);
                        bFind=true;
                        break;
                    }
                }
                //满2个任务才做
                if (UtilsGui.modeConf.m_id == UiItemConst.模式_自动佣兵任务.m_id
                    && TaskUtils.GetTaskList().Count<2)
                {
                    UtilsLog.Log("[地图信息识别] 任务没满2个，我要去2-5刷神秘人了");
                    bFind = false;
                }
                m_bNeedComplete = bFind?true:false;
                if (!bFind)
                {
                    UtilsLog.Log("[地图信息识别] 任务地图没找到，我要去2-5混了");
                    m_currMap = MapConst.N2_5;
                }
            }
            else if (UtilsGui.modeConf.m_id == UiItemConst.模式_自动解锁装备.m_id)
            {
                m_bNeedComplete=true;
                InitMap();
				if (unlockMapID.Count > 0)
				{
					UtilsLog.Log(string.Format("自动解锁装备地图ID:{0}", unlockMapID[0]));
                    m_currMap = GetMapFromId(unlockMapID[0]);
				}
				else
				{
					UtilsLog.Log(string.Format("无待解锁装备地图"));
                    m_currMap = GetUnCompleteMap();
				}
            }
            m_currMap=EnsureMapHasUnlock(m_currMap);

            //选择
            LettuceVillageDisplay.LettuceSceneTransitionPayload lettuceSceneTransitionPayload =
                new LettuceVillageDisplay.LettuceSceneTransitionPayload();
            LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(m_currMap.m_id);
            lettuceSceneTransitionPayload.m_SelectedBounty = record;
            lettuceSceneTransitionPayload.m_SelectedBountySet = record.BountySetRecord;
            lettuceSceneTransitionPayload.m_DifficultyMode = ((Assets.LettuceBounty.MercenariesBountyDifficulty)(record.Heroic ? 2 : 1));
            SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_BOUNTY_TEAM_SELECT,
                SceneMgr.TransitionHandlerType.CURRENT_SCENE, null, lettuceSceneTransitionPayload);
        }

        public static Map GetMapFromId(int id)
        {
            return MapConst.GetMapList().Find(
                (Map m) => m.m_id==id);
        }

        public static Map GetMapFromName(string name)
        {
            return MapConst.GetMapList().Find(
                (Map m) => m.m_name.Equals(name));
        }

        public static Map GetMapByBoss(string boss)
        {
            return MapConst.GetMapList().Find(
                (Map m) => m.m_boss.Equals(boss));
        }

        public static Map GetUnCompleteMap()
        {
            for (int i = 0; i < MapConst.GetMapList().Count; i++)
            {
                if (!MercenariesDataUtil.IsBountyComplete(
                    MapConst.GetMapList()[i].m_id))
                {
                    return MapConst.GetMapList()[i];
                }
            }
            return MapConst.H1_1;
        }

        public static bool MapCompleted(Map map)
        {
            if(null==map) return false;
            LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(map.m_id);
            if (record.RequiredCompletedBounty > 0 &&
                !MercenariesDataUtil.IsBountyComplete(record.RequiredCompletedBounty))
            {
                return false;
            }
            return true;
        }

        public static Map EnsureMapHasUnlock(Map map)
        {
            LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(map.m_id);

            if (record.RequiredCompletedBounty > 0)
            {
                //1.非第一小关
                if (false == MercenariesDataUtil.IsBountyComplete(record.RequiredCompletedBounty))
                    return UtilsMap.GetUnCompleteMap();
            }
            else
            {
                if (map.m_id == 57 || map.m_id == 85)
                    return map;
                if ((map.m_id == 67 || map.m_id == 94) && false == MercenariesDataUtil.IsBountyComplete(65))
                    return UtilsMap.GetUnCompleteMap();
                if ((map.m_id == 73 || map.m_id == 100) && false == MercenariesDataUtil.IsBountyComplete(72))
                    return UtilsMap.GetUnCompleteMap();
                else if (false == MercenariesDataUtil.IsBountyComplete(78))
                    return UtilsMap.GetUnCompleteMap();
            }
            return map;
        }

        public static QueueList<int> unlockMercID = new QueueList<int>();
		public static QueueList<int> unlockMapID = new QueueList<int>();
        public static void InitMap()
		{
            Dictionary<int, int> equipMapId = new Dictionary<int, int>();
            equipMapId.Clear();
            var equipTierByMap = GameDbf.BonusBountyDropChance.GetRecords();
            foreach (var item in equipTierByMap)
            {
                var tierRecord = GameDbf.LettuceEquipmentTier.GetRecord(item.LettuceEquipmentTierId);
                if (tierRecord != null)
                {
                    LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(item.LettuceBountyRecord.ID);
                    if (record.RequiredCompletedBounty > 0 && !MercenariesDataUtil.IsBountyComplete(record.RequiredCompletedBounty))
                    { //地图未解锁
                        continue;
                    }
                    else
                    {
                        equipMapId.Add(tierRecord.LettuceEquipmentId, item.LettuceBountyRecord.ID);
                        //Out.Log(string.Format("待解锁的装备ID:{0},待解锁的地图ID：{1}",tierRecord.LettuceEquipmentId, item.LettuceBountyRecord.ID));
                    }
                }
            }
            unlockMercID.Clear();
            unlockMapID.Clear();
            List<LettuceMercenary> mercenaries = CollectionManager.Get().FindMercenaries(null, new bool?(true), null, null, null,true).m_mercenaries;

            foreach (var MercID in MercConst.First)
            {   //遍历优先解锁佣兵队列
                LettuceMercenary mercenary2 = UtilsMerc.GetMercenaryFromId(MercID);
                foreach (var equip in mercenary2.m_equipmentList) // 遍历当前佣兵的装备列表
                {
                    if (!equip.Owned && mercenary2.m_owned) // 如果当前装备没有获得 && 当前佣兵已经合成
                    {
                        if (equipMapId.ContainsKey(equip.ID)) //如果未获得的装备已经在字典中
                        {
                            //将佣兵id + 地图id 加入队列
                            unlockMercID.Enqueue(mercenary2.ID);
                            unlockMapID.Enqueue(equipMapId[equip.ID]);
                            //Out.Log(string.Format("待解锁的佣兵：{0} ID: {1} 地图ID: {2}",merc.m_mercName,merc.ID, equipMapId[equip.ID]));

                        }
                    }
                }
            }
            foreach (var merc in mercenaries) // 遍历所有的佣兵
            {
                if (!MercConst.First.Contains(merc.ID))//如果这个佣兵不是优先解锁
                {
                    foreach (var equip in merc.m_equipmentList) // 遍历当前佣兵的装备列表
                    {
                        if (!equip.Owned && merc.m_owned) // 如果当前装备没有获得 && 当前佣兵已经合成
                        {
                            if (equipMapId.ContainsKey(equip.ID)) //如果未获得的装备已经在字典中
                            {
                                //将佣兵id + 地图id 加入队列
                                unlockMercID.Enqueue(merc.ID);
                                unlockMapID.Enqueue(equipMapId[equip.ID]);
                                //Out.Log(string.Format("待解锁的佣兵：{0} ID: {1} 地图ID: {2}",merc.m_mercName,merc.ID, equipMapId[equip.ID]));

                            }
                        }
                    }
                }
            }
        }
    }
}